import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/home'
import { GET_TOKEN } from '@/utils/token'
import nprogress from 'nprogress'
// 引入进度条样式
import 'nprogress/nprogress.css'
nprogress.configure({ showSpinner: false })
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/index' },
  {
    path: '/index',
    name: 'Home',
    meta: {
      title: '首页' // 设置该路由在浏览器标签显示的title
    },
    component: HomeView
  },
  {
    path: '/artclelist',
    name: 'Artclelist',
    meta: {
      title: '文章列表' // 设置该路由在浏览器标签显示的title
    },
    component: () => import('@/views/artcle')
  },
  {
    path: '/artcle/:id',
    name: 'ArtclePage',
    meta: {
      title: '文章详情页' // 设置该路由在浏览器标签显示的title
    },
    component: () => import('@/views/artcle/ArtclePage')
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登录' // 设置该路由在浏览器标签显示的title
    },
    component: () => import('@/views/login')
  },
  {
    path: '*',
    component: () => import('@/views/404')
  }
]

const router = new VueRouter({
  routes
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('全局前置守卫')
  console.log('from: ', from)
  console.log('to: ', to)
  // 进度条开始
  nprogress.start()
  if (to?.meta?.title) {
    document.title = to.meta.title
  }
  // 在这里执行你的逻辑
  // 例如，检查用户是否登录
  const token = GET_TOKEN()

  if (!token) {
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login' })
      nprogress.done()
    }
  } else {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 否则，继续导航
      next()
    }
  }
})
// 全局后置守卫
router.afterEach(() => {
  console.log('全局后置守卫')
  nprogress.done()
})
export default router
